<template>
  <div id="DigitalModelBase">
    <div style="width: 1300px; margin-bottom: 10px">
      <span style="color: white">课程信息：</span>
      <a-select v-model="curriculumId" style="width: 180px">
        <a-select-option
          v-for="item in curriculumIdList"
          :key="item.id"
          :value="item.id"
          >{{ item.name }}</a-select-option
        >
      </a-select>
      <span style="color: white; margin-left: 30px">关键字：</span>
      <a-input style="width: 200px; color: white" v-model="keyword"></a-input>
      <a-button type="primary" style="margin-left: 10px" @click="getData"
        >查询</a-button
      >
      <a-button type="primary" style="margin-left: 10px" @click="leadInto"
        >导入</a-button
      >
      <a-button type="primary" style="margin-left: 10px" @click="downClick"
        >导出</a-button
      >
    </div>
    <a-table
      :scroll="{ y: 580 }"
      :columns="columns"
      style="margin-top: 16px"
      :data-source="tableData"
      :pagination="tablePagination"
      :row-selection="{
        selectedRowKeys: selectedRowKeys,
        onChange: onSelectChange,
      }"
      :rowKey="(record, index) => record.id"
      @change="handleTableChange"
    >
      <template slot="name" slot-scope="text, record">
        <a-tooltip placement="top" v-if="record.name">
          <template slot="title">
            <span>{{ record.name }}</span>
          </template>
          <span style="cursor: default">{{ record.name }}</span>
        </a-tooltip>
        <span v-else-if="!record.name">—</span>
      </template>
      <template slot="tapdProjectId" slot-scope="text, record">
        <a-tooltip placement="top" v-if="record.tapdProjectId">
          <template slot="title">
            <p>{{ record.tapdProjectId }}</p>
          </template>
          <span style="cursor: default">{{ record.tapdProjectId }}</span>
        </a-tooltip>
        <span v-else-if="!record.tapdProjectId">—</span>
      </template>
      <template slot="operation" slot-scope="text, record">
        <a-button
          v-if="record.operation"
          type="primary"
          @click="editClick(record)"
          style="margin-right: 10px"
          >修改</a-button
        >
        <a-button
          v-if="record.operation"
          type="danger"
          @click="deleteClick(record)"
          >删除</a-button
        >
      </template>
    </a-table>
    <a-modal
      v-model="visible"
      :maskClosable="false"
      :title="title"
      :footer="null"
    >
      <a-form-model
        :label-col="{ span: 5 }"
        :wrapper-col="{ span: 12 }"
        ref="formRef"
        :model="form"
        :rules="rules"
      >
        <a-form-model-item label="课程信息" prop="curriculumId">
          <a-select v-model="form.curriculumId" style="width: 236px">
            <a-select-option
              v-for="item in curriculumIdList"
              :key="item.id"
              :value="item.id"
              >{{ item.name }}</a-select-option
            >
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="数据描述" prop="description">
          <a-input v-model="form.description" />
        </a-form-model-item>
        <a-form-model-item label="文件导入">
          <a-button
            v-if="!form.description || !form.curriculumId"
            type="primary"
            @click="messageShow"
            >导入</a-button
          >
          <a-upload
            v-else
            ref="uploadRef"
            class="upload"
            name="file"
            :data="getUploadParams"
            :before-upload="handleBeforeUpload"
            :multiple="true"
            :show-upload-list="false"
            :custom-request="customUploadRequest"
          >
            <a-button type="primary" style="margin-left: 8px">导入</a-button>
          </a-upload>
        </a-form-model-item>
      </a-form-model>
      <!-- <template slot="footer">
        <a-button key="back" class="modalCancel" @click="handleCancel"
          >取消</a-button
        >
        <a-button key="submit" @click="primaryClick" type="primary">
          确定
        </a-button>
      </template> -->
    </a-modal>
  </div>
</template>
  <script>
export default {
  data() {
    return {
      keyword: null,
      curriculumId: null,
      curriculumIdList: [],
      form: {
        curriculumId: "", // 课程信息
        description: "", //课程描述
      },
      rules: {
        curriculumId: [
          { required: true, message: "请选择课程信息", trigger: "blur" },
        ],
        description: [
          { required: true, message: "请输入数据描述", trigger: "blur" },
        ],
      },
      visible: false,
      title: null,
      selectedRowKeys: [],
      columns: [
        //主页table列的配置
        {
          title: "数据名称",
          dataIndex: "fileName",
          customRender: (text, record) => {
            return record.fileName ? record.fileName : "—";
          },
        },
        {
          title: "创建时间",
          dataIndex: "createTime",
          customRender: (text, record) => {
            return record.createTime ? record.createTime : "—";
          },
        },
        {
          title: "数据描述",
          dataIndex: "description",
          customRender: (text, record) => {
            return record.description ? record.description : "—";
          },
        },
        {
          title: "操作",
          width: 180,
          dataIndex: "operation",
          scopedSlots: { customRender: "operation" },
        },
      ],
      tableData: [
        //主页表格的数据
      ],
      tablePagination: {
        //主页表格的分页器
        total: 0,
        current: 1,
        pageSize: 10,
        showQuickJumper: true, //是否可以快速跳转至某页
        showSizeChanger: true, //是否可以改变 pageSize
      },
    };
  },
  created() {
    this.getData();
    this.getCurriculumIdList();
  },
  computed: {},
  methods: {
    downClick() {
      if (this.selectedRowKeys.length != 1) {
        this.$message.warning("需要选中数据且仅能选中一条");
      } else {
        let obj = this.tableData.find(
          (item) => item.id === this.selectedRowKeys[0]
        );
        this.$axios
          .get("/digital/model/download", {
            params: {
              id: this.selectedRowKeys[0],
            },
            responseType: "blob", // 关键：指定返回数据类型为 blob
          })
          .then((res) => {
            const downloadUrl = window.URL.createObjectURL(res);
            const link = document.createElement("a"); // 创建隐藏的下载链接
            link.href = downloadUrl;
            const filename = obj.fileName; //文件名可以从响应头或请求参数中获取
            link.download = filename;
            link.click();
            link.remove();
          });
      }
    },
    messageShow() {
      if (!this.form.curriculumId) {
        this.$message.warning("请选择课程信息");
      } else if (!this.form.description) {
        this.$message.warning("请输入课程描述");
      }
    },
    leadInto() {
      this.title="导入";
      this.visible = true;
    },
    getCurriculumIdList() {
      //获取课程基础信息的下拉
      this.$axios.get("/curriculum/options").then((res) => {
        this.curriculumIdList = res.data;
      });
    },
    handleTableChange(pagination, filters, sorter) {
      this.tablePagination.current = pagination.current;
      this.tablePagination.pageSize = pagination.pageSize;
      this.getData();
    },
    onSelectChange(selectedRowKeys) {
      console.log("selectedRowKeys changed: ", selectedRowKeys);
      this.selectedRowKeys = selectedRowKeys;
    },
    deleteClick(row) {
      //点击删除
      let params = {
        id: row.id,
      };
      let that = this;
      this.$confirm({
        title: "确认删除?",
        content: "您确定要删除此项吗?",
        onOk() {
          that.$axios.delete("/digital/model/delete", { params }).then((res) => {
            if (res.code == 200) {
              that.$message.success("删除成功");
              that.getData();
            }
          });
        },
        onCancel() {
          console.log("取消删除");
        },
      });
    },
    getUploadParams(file) {
      // 动态返回参数，根据文件的类型、大小等来决定要上传的参数
      return {
        name: file.name, //文件名
        desc: null, //文件描述
        type: file.type, // 文件类型
        coursePlanId: this.coursePlanId, //课程计划id
      };
    },
    handleBeforeUpload(file) {
      //文件上传的上传文件弹出框弹出之前的回调
      return true;
    },
    customUploadRequest({ file, onSuccess, onError }) {
      const formData = new FormData();
      // 添加文件到 FormData
      formData.append("file", file);
      // 如果需要其他参数，可以在这里添加
      // formData.append('additionalParam', 'value');
      let params = {
        curriculumId: this.form.curriculumId,
        description: this.form.description,
      };
      this.$axios
        .post("/digital/model/upload/file", formData, { params })
        .then((res) => {
          if (res.code == 200) {
            this.$message.success("上传成功");
            this.visible = false;
            this.getData();
          }
        });
    },
    async getData() {
      let { data } = await this.$axios.get("/digital/model/page/list", {
        //根据类型查询该类型的所有数据
        params: {
          keyword: this.keyword,
          page: this.tablePagination.current,
          size: this.tablePagination.pageSize,
          curriculumId: this.curriculumId,
        },
      });
      this.tableData = data.records;
      this.tablePagination.total = data.total;
    },
    editClick(row) {
      //编辑
      this.title = "编辑";
      this.$axios.get("/digital/model/detail",{
        params:{
          id:row.id
        }
      }).then(res=>{
        if (res.code==200) {
          this.form.curriculumId=res.data.curriculumId;//课程信息
          this.form.description=res.data.description;//课程描述
          this.visible = true;
        }
      })      
    },
    addbtn() {
      //新增
      this.title = "新增";
      this.visible = true;
    },
    handleCancel() {
      for (let i in this.form) {
        this.form[i] = null;
      }
      this.$refs.formRef.resetFields();
      this.visible = false;
    },
    primaryClick() {
      this.handleCancel();
      // this.$nextTick(() => {
      //   this.$refs.formRef.validate((valid) => {
      //     if (valid) {
      //       console.log("提交成功:", this.form);
      //       this.visible = false; // 关闭模态框
      //     } else {
      //       console.log("校验失败");
      //     }
      //   });
      // });
    },
  },
};
</script>
<style lang="scss" scoped>
#DigitalModelBase {
  background: #ffffff;
  padding: 24px 32px;
  margin: 30px 20px 0 20px;
  border-radius: 2px;
}
</style>
<style lang="scss">
#DigitalModelBase {
  height: 800px;
  background: url("~@/assets/img/tableDataBg.png") repeat 100% !important;
  background-size: cover !important;
}
</style>